package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.dto.ApCommentVo;
import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.entity.UpdateArticleMessage;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreenTextScan textScan;




    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //判断内容是否大于140字
        if(dto==null||dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断用户是否登录（需要使用手机号和密码登录的用户）
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //安全过滤-阿里云审核
        try {
            Map map = textScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if(suggestion.equals("block")){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApComment apComment=new ApComment();
        apComment.setAuthorId(user.getUserId());
        ResponseResult<ApUser> userResponseResult = userFeign.getById(user.getUserId());
        if(userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUser apUser = userResponseResult.getData();
            apComment.setAuthorName(apUser.getName());
            apComment.setImage(apUser.getImage());
        }
        apComment.setEntryId(dto.getArticleId());
        apComment.setChannelId(dto.getChannelId());
        apComment.setType(0);
        apComment.setLikes(0);
        apComment.setContent(dto.getContent());
        apComment.setReply(0);
        apComment.setFlag(0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.save(apComment);
        UpdateArticleMessage  message=new UpdateArticleMessage();
        message.setAdd(1);
        message.setArticleId(dto.getArticleId());
        message.setType(2);
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(commentTopic,value);
        return ResponseResult.okResult();

    }
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Value("${topic.commentTopic}")
    private String commentTopic;

    /**
     * 点赞评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //获取当前的用户
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApCommentLike like=new ApCommentLike();
        like.setAuthorId(user.getUserId());
        like.setCommentId(dto.getCommentId());
        like.setOperation(dto.getOperation());
        //判断当前用户是否对这篇评论有过点赞记录
        Query query=new Query();
        query.addCriteria(Criteria.where("authorId").is(user.getUserId()));
        query.addCriteria(Criteria.where("CommentId").is(dto.getCommentId()));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
        if(one==null){
            mongoTemplate.save(like);
            //更新评论表的点赞数量
            Query commentQuery=new Query();
            commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
            Update update=new Update();
            update.inc("likes");
            mongoTemplate.updateFirst(commentQuery,update,ApComment.class);
        }else{
            if(one.getOperation()!=dto.getOperation()){
                //判断是否点赞还是取消点赞
                int add=1;
                //修改aplike的状态
                one.setOperation(dto.getOperation());
                mongoTemplate.save(one);
                //更新评论表的点赞数量
                if(dto.getOperation()==1){
                    add=-1;
                }
                Query commentQuery=new Query();
                commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
                Update update=new Update();
                update.inc("likes",add);
                mongoTemplate.updateFirst(commentQuery,update,ApComment.class);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 加载评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(CommentDto dto) {
        //根据文章id查询评论列表
        //按照创建时间倒叙排列
        //分页判断数据小于前端传递的最小时间
        //每页默认显示10
        if(dto.getSize()==null||dto.getSize()<0||dto.getSize()>=50){
            dto.setSize(10);
        }
        Query query=new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        query.addCriteria(Criteria.where("createdTime").lt(dto.getMinDate()));
        Pageable page= PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"createdTime");
        query.with(page);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        //判断当前用户是否登录
        User user = AppThreadLocalUtil.get();
        List<ApCommentLike> likes=new ArrayList<>();
        //登录用户后查看当前返回列表是否有点赞记录
        if(user !=null){
            List<String> commentIds=new ArrayList<>();
            for (ApComment apComment : apComments) {
                commentIds.add(apComment.getId());
            }
            Query likeQuery=new Query();
            likeQuery.addCriteria(Criteria.where("authorId").is(user.getUserId()));
            likeQuery.addCriteria(Criteria.where("commentId").in(commentIds));
            likeQuery.addCriteria(Criteria.where("operation").is(0));
            likes = mongoTemplate.find(likeQuery, ApCommentLike.class);
        }
        List<String> existCommentIds=new ArrayList<>();
        for (ApCommentLike like : likes) {
            existCommentIds.add(like.getCommentId());
        }
        List<ApCommentVo> vos=new ArrayList<>();
        for (ApComment apComment : apComments) {
            ApCommentVo vo=new ApCommentVo();
            BeanUtils.copyProperties(apComment,vo);
            vo.setOperation(1);
            if(existCommentIds.contains(apComment.getId())){
                vo.setOperation(0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }
}
